/**
 * Created by PanJiaChen on 16/11/18.
 */
import FileSaver from "file-saver";
import * as XLSX from 'xlsx/xlsx.mjs';

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

export const cityOptions = [{
  "name": "淄川区",
  "key": "370302"
}, {
  "name": "张店区",
  "key": "370303"
}, {
  "name": "博山区",
  "key": "370304"
}, {
  "name": "临淄区",
  "key": "370305"
}, {
  "name": "周村区",
  "key": "370306"
}, {
  "name": "桓台县",
  "key": "370321"
}, {
  "name": "高青县",
  "key": "370322"
}, {
  "name": "沂源县",
  "key": "370323"
}, {
  "name": "经开区",
  "key": "370325"
}, {
  "name": "高新区",
  "key": "370326"
}]

export const businessOptions = [{
  "name": "技改专项贷",
  "key": "技改专项贷"
}, {
  "name": "农业龙头贷",
  "key": "农业龙头贷"
}, {
  "name": "流动资金贷款",
  "key": "流动资金贷款"
}, {
  "name": "创业担保组合贷",
  "key": "创业担保组合贷"
}, {
  "name": "一般融资",
  "key": "一般融资"
}, {
  "name": "股权质押",
  "key": "股权质押"
}, {
  "name": "银行承兑",
  "key": "银行承兑"
}, {
  "name": "科技贷",
  "key": "科技贷"
}]

export const contractOptions = [{
  "name": "委托担保合同",
  "key": "委托担保合同"
}, {
  "name": "反担保-房产抵押",
  "key": "反担保-房产抵押"
}, {
  "name": "反担保-设备抵押",
  "key": "反担保-设备抵押"
}, {
  "name": "反担保-其他抵押",
  "key": "反担保-其他抵押"
}, {
  "name": "反担保-股权质押",
  "key": "反担保-股权质押"
}, {
  "name": "反担保-专利质押",
  "key": "反担保-专利质押"
}, {
  "name": "反担保-应收账款质押",
  "key": "反担保-应收账款质押"
}, {
  "name": "反担保-其它质押",
  "key": "反担保-其它质押"
}, {
  "name": "反担保-企业保证",
  "key": "反担保-企业保证"
}, {
  "name": "反担保-个人保证",
  "key": "反担保-个人保证"
}]


export const contractStatus = [ {
  "name": "未发起",
  "key": "未发起"
},{
  "name": "签署完成",
  "key": "签署完成"
}, {
  "name": "甲方签署中",
  "key": "甲方签署中"
}, {
  "name": "乙方签署中",
  "key": "乙方签署中"
}]

export function exportXlsx(cssSelector,name = '表格'){
  //前端分业算法
  //https://blog.csdn.net/weixin_45502613/article/details/109745994

  var xlsxParam = { raw: true };
  let wb = XLSX.utils.table_to_book(
    document.querySelector(cssSelector),
    xlsxParam
  );
  console.log('exportXlsx',wb);
  let wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array"
  });
  try {
    FileSaver.saveAs(
      new Blob([wbout], { type: "application/octet-stream" }),
      `${name}.xlsx`
    )
    
  } catch (e) {
    if (typeof console !== "undefined") console.log(e, wbout);
  }
}

export function getTableList(pageNum, pageSize, Data = []){//前端分页算法
  const total = Data.length
  if(!total){
      return []
  }
  if(total <= pageSize){
      return Data
  }
  const num = pageSize * (pageNum - 1);//计算当前页（不含）之前的所有数据总条数
  if (num < total) { //如果当前页之前所有数据总条数小于（不能等于）总的数据集长度，则说明当前页码没有超出最大页码
      const startIndex = num;//当前页第一条数据在总数据集中的索引
      const endIndex = num + pageSize - 1;//当前页最后一条数据索引
      return Data.filter((_, index) => index >= startIndex && index <= endIndex);//当前页数据条数小于每页最大条数时，也按最大条数范围筛取数据
  } else { //当前页码超出最大页码，则计算实际最后一页的page，自动返回最后一页数据
      const size = parseInt(total / pageSize); //取商
      const rest = total % pageSize; //取余数
      if (rest > 0) { //余数大于0，说明实际最后一页数据不足pageSize，应该取size+1为最后一条的页码
              return Data.filter((_, index) => index >= (pageSize * size) && index <= total);
      } else if (rest === 0) { //余数等于0，最后一页数据条数正好是pageSize
              return Data.filter((_, index) => index >= (pageSize * (size - 1)) && index <= total);
      } //注：余数不可能小于0
  }
}